#include "alertmanager.h"
#include "core/databasepool/databasepool.h"
#include <QSqlQuery>
#include <QDateTime>
#include <QVariant>
#include <QDebug>

void AlertManager::createAlertRuleTable() {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.exec(R"(
        CREATE TABLE IF NOT EXISTS alarm_rules (
            rule_id INTEGER PRIMARY KEY AUTOINCREMENT,
            device_id INTEGER NOT NULL,
            description TEXT NOT NULL,
            condition TEXT NOT NULL,
            action TEXT NOT NULL,
            FOREIGN KEY (device_id) REFERENCES devices(device_id)
    )");
    DatabasePool::instance().releaseConnection(db);
}

void AlertManager::createAlertRecordTable() {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.exec(R"(
        CREATE TABLE IF NOT EXISTS alarm_records (
            alarm_id INTEGER PRIMARY KEY AUTOINCREMENT,
            device_id INTEGER NOT NULL,
            timestamp TEXT NOT NULL,
            content TEXT NOT NULL,
            status TEXT NOT NULL,
            note TEXT,
            FOREIGN KEY (device_id) REFERENCES devices(device_id)
        )
    )");
    DatabasePool::instance().releaseConnection(db);
}

AlertManager::AlertManager(QObject* parent) : QObject(parent) {
    createAlertRuleTable();
    createAlertRecordTable();
}

bool AlertManager::addAlertRule(int deviceId, const QString& description, const QString& condition, const QString& action) {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.prepare("INSERT INTO alarm_rules (device_id, description, condition, action) VALUES (?, ?, ?, ?)");
    query.addBindValue(deviceId);
    query.addBindValue(description);
    query.addBindValue(condition);
    query.addBindValue(action);
    bool success = query.exec();
    DatabasePool::instance().releaseConnection(db);
    if(success) emit dataUpdated();
    return success;
}

bool AlertManager::deleteAlertRule(int ruleId) {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.prepare("DELETE FROM alarm_rules WHERE rule_id = ?");
    query.addBindValue(ruleId);
    bool success = query.exec();
    DatabasePool::instance().releaseConnection(db);
    if(success) emit dataUpdated();
    return success;
}

bool AlertManager::recordAlert(int deviceId, const QString& content, const QString& status, const QString& note) {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.prepare("INSERT INTO alarm_records (device_id, timestamp, content, status, note) VALUES (?, ?, ?, ?, ?)");
    query.addBindValue(deviceId);
    query.addBindValue(QDateTime::currentDateTime().toString(Qt::ISODate));
    query.addBindValue(content);
    query.addBindValue(status);
    query.addBindValue(note);
    bool success = query.exec();
    DatabasePool::instance().releaseConnection(db);
    return success;
}

void AlertManager::checkAlertRules(int deviceId, double temperature, double humidity, double light, double co2, double pressure) {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.prepare("SELECT description, condition, action FROM alarm_rules WHERE device_id = ?");
    query.addBindValue(deviceId);

    if (query.exec()) {
        while (query.next()) {
            QString condition = query.value(1).toString();
            bool triggered = false;

            // 示例解析逻辑（需根据实际规则格式完善）
            if (condition.contains("temperature")) {
                QStringList parts = condition.split(' ');
                if (parts.size() >= 3) {
                    QString op = parts[1];
                    double threshold = parts[2].toDouble();
                    if (op == ">" && temperature > threshold) triggered = true;
                    else if (op == "<" && temperature < threshold) triggered = true;
                }
            }
            // Add similar checks for other parameters
            if(triggered) {
                QString description = query.value(0).toString();
                emit alertTriggered(deviceId, description);
                recordAlert(deviceId, description, "未处理");
                notifyAdmin(deviceId, description);
            }
        }
    }
    DatabasePool::instance().releaseConnection(db);
}

void AlertManager::notifyAdmin(int deviceId, const QString& description) {
    // Implement actual notification logic here
    qDebug() << "Alert! Device" << deviceId << ":" << description;
}
